import Vue from "vue";
import VueRouter from "vue-router";
import Home from "@/views/layout/Index.vue";
import Welcome from "@/views/welcome/Index.vue";
import store from "@/store";
const Login = () => import("@/views/login/Index.vue");
const Passenger = () => import("@/views/passenger/Index.vue");
const dailyTrainTicket = () => import("@/views/ticket/Index.vue");
const order = () => import("@/views/order/Index.vue");
const myTicket = () => import("@/views/my-ticket/Index.vue");

Vue.use(VueRouter);

const routes = [
  {
    path: "/login",
    component: Login,
  },
  {
    path: "/",
    component: Home,
    meta: {
      requiresAuth: true,
    },
    redirect: "/welcome",
    children: [
      {
        path: "/welcome",
        component: Welcome,
        meta: {
          requiresAuth: true,
        },
      },
      {
        path: "/passenger",
        component: Passenger,
        meta: {
          requiresAuth: true,
        },
      },
      {
        path: "/train/ticket",
        name: "dailyTrainTicket",
        component: dailyTrainTicket,
        meta: {
          requiresAuth: true,
        },
      },
      {
        path: "/order",
        name: "order",
        component: order,
        meta: {
          requiresAuth: true,
        },
      },
      {
        path: "/my-ticket",
        name: "myTicket",
        component: myTicket,
        meta: {
          requiresAuth: true,
        },
      },
    ],
  },
];

const router = new VueRouter({
  mode: "history",
  base: process.env.BASE_URL,
  routes,
});

router.beforeEach((to, from, next) => {
  //获取token
  const token = store.getters.getToken;
  //需要登录
  if (to.matched.some((item) => item.meta.requiresAuth)) {
    //已经登录
    if (token) {
      next();
    } else {
      //未登录重定向到登录页面
      next(`/login?redirect=${to.fullPath}`);
    }
  } else {
    //登录了，但是去登录页, 就跳回到当前页
    if (token && to.path === "/login") {
      next(from.fullPath);
    }
    //不需要登录直接访问
    next();
  }
});

export default router;
